import 'dart:io';

import 'package:city_pickers/city_pickers.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:part_time_job_pro/common/index.dart';
import 'package:part_time_job_pro/pages/public/part/detail/view.dart';
import 'package:part_time_job_pro/pages/public/part/state.dart';

class PartJobLogic extends BaseController {
  final PartJobState state = PartJobState();

  final ScrollController scrollController = ScrollController();

  ///输入监听
  late TextEditingController jobNameTextEditController;
  late TextEditingController addJobNameTextEditController;
  late TextEditingController addressTextEditController;
  late TextEditingController workContentEditController;
  late TextEditingController jobSearchEditController;

  ///监听是否正在输入数据
  late FocusNode jobNameFocusNode;
  late FocusNode addJobNameFocusNode;
  late FocusNode addressTextFocusNode;
  late FocusNode workContentFocusNode;
  late FocusNode jobSearchFocusNode;

  //初始化
  @override
  void onInit() {
    super.onInit();

    initFocusNode();
    initPageData();

    scrollController.addListener(() {
      double offset = scrollController.offset; // 当前滚动偏移量
      print('当前滚动位置: $offset');
      state.scrollBarThickness = 2.0;
      Future.delayed(
        const Duration(seconds: 1),
        () {
          state.scrollBarThickness = 0.0;
          update();
        },
      );
    });
  }

  //注销函数
  @override
  void onClose() {
    jobNameTextEditController.dispose();
    addressTextEditController.dispose();
    workContentEditController.dispose();
    scrollController.dispose();
    super.onClose();
  }

  ///监听是否在输入密码或验证码
  initFocusNode() {
    //设置默认值，光标在文字最后
    workContentEditController = TextEditingController.fromValue(
        TextEditingValue(
            text: state.hinTextValue,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream,
                offset: state.hinTextValue.length))));
    addressTextEditController = TextEditingController();
    jobNameTextEditController = TextEditingController();
    addJobNameTextEditController = TextEditingController();
    jobSearchEditController = TextEditingController();
    jobNameFocusNode = FocusNode();
    addJobNameFocusNode = FocusNode();
    jobSearchFocusNode = FocusNode();
    addressTextFocusNode = FocusNode();
    workContentFocusNode = FocusNode();

    //监听输入焦点
    addressTextFocusNode.addListener(() {
      if (addressTextFocusNode.hasFocus) {
        // 焦点获得时的操作
        state.isShowNextStepButton = false;
        update();
      } else {
        // 焦点失去时的操作
        state.isShowNextStepButton = true;
        update();
      }
    });

    jobSearchFocusNode.addListener(() {
      if (jobSearchFocusNode.hasFocus) {
        state.isSearchInput = true;
        update();
      } else {
        state.isSearchInput = false;
        update();
      }
    });
  }

  //页面部分数据初始化
  initPageData() {
    LogUtil.e("=======initPageData========");
    getPartJobTypeList();
    //从缓存中获取上次编辑的数据 并且提示
  }

  //清空名称输入
  clearJobName() {
    state.jobName = '';
    state.jobNameLength = 0;
    jobNameTextEditController.clear();
    jobNameFocusNode.unfocus();
    update();
  }

  ///监听名称输入
  updateJobName(String text) {
    state.jobName = text;
    changeMaxLimit(text);
    update();
  }

  //清空名称输入
  clearAddJobName() {
    state.addJobName = '';
    state.jobNameLength = 0;
    addJobNameTextEditController.clear();
    addJobNameFocusNode.unfocus();
    update();
  }

  ///监听名称输入
  updateAddJobName(String text) {
    state.addJobName = text;
    update();
  }

  //清空搜索输入
  clearJobSearchName() {
    state.jobSearchName = '';
    state.searchDataList = [];
    jobSearchEditController.clear();
    jobSearchFocusNode.unfocus();
    update();
  }

  /// 改字数限制，每输入一个中文字符，要减1。
  /// 字符要求：10个汉字或20个英文
  var maxLength;

  void changeMaxLimit(String value) {
    var originNum = 10;
    maxLength = originNum * 2;
    var zhCnNum = 0;
    var enNum = 0;
    for (int i = 0; i < value.length; i++) {
      if (zhCnNum * 2 + enNum < originNum * 2) {
        if (value.codeUnitAt(i) > 122) {
          //累计中文个数
          zhCnNum++;
        } else {
          //累计英文个数
          enNum++;
        }
      } else {
        var correct1 = originNum - enNum / 2;
        //如果超出，修正中文个数
        if (zhCnNum > correct1) {
          zhCnNum = correct1 as int;
        }
        //如果超出，修正英文个数
        var correct2 = originNum * 2 - zhCnNum * 2;
        if (enNum > correct2) {
          enNum = correct2;
        }
        //重设最大长度
        maxLength = zhCnNum + enNum;
        jobNameTextEditController.text = value.substring(0, maxLength);
        //光标移到最后
        jobNameTextEditController.selection = TextSelection.fromPosition(
            TextPosition(affinity: TextAffinity.downstream, offset: maxLength));
        break;
      }
      state.jobNameLength = enNum + zhCnNum * 2;
      LogUtil.e(enNum, tag: "en_num");
      LogUtil.e(zhCnNum, tag: "zh_cn_num");
      update();
    }
  }

  ///监听搜索输入
  updateJobSearchName(String text) {
    state.jobSearchName = text;
    LogUtil.e(state.jobSearchName, tag: "搜索词：");
    if (text.isNotEmpty) {
      state.searchDataList = [];
      state.searchDataList = searchTypeList(text);
      //打印数据
      if (state.searchDataList.isNotEmpty) {
        for (int i = 0; i < state.searchDataList.length; i++) {
          LogUtil.e(state.searchDataList[i].typeName, tag: "匹配数据：");
        }
      }
    } else {
      state.searchDataList = [];
    }
    update();
  }

  //递归搜索集合数据
  searchTypeList(String targetName) {
    List<PartJobType> typeList = [];
    if (targetName.isNotEmpty) {
      typeList = findPartJobTypeByName(targetName);
      LogUtil.e(typeList, tag: "typeList");
    }
    return typeList;
  }

  //搜索列表点击
  clickSearchList(PartJobType jobType) {
    String? ancestors = jobType.ancestors;
    LogUtil.e("ancestors==$ancestors");
    if (ancestors != null) {
      List<String> parentIds = ancestors.split(",");
      if (parentIds.length == 3) {
        state.firstCheckedType = findPartJobTypeById(int.parse(parentIds[1]));
        //根据一级获取二级数据
        state.secondLevelList = findChildrenByTypeId(int.parse(parentIds[1]));
        //设置二级选中
        state.secondCheckedType = findPartJobTypeById(int.parse(parentIds[2]));
        //根据二级获取三级数据
        state.thirdLevelList = findChildrenByTypeId(int.parse(parentIds[2]));
        //设置三级选中
        state.thirdCheckedType = jobType;
        state.tempPartTypeName = state.secondCheckedType?.typeName;
        state.selectPartTypeText =
            "${state.firstCheckedType?.typeName}/${state.secondCheckedType?.typeName}/${jobType.typeName}";
        //处理上级行号
        state.checkedRowIndex =
            findRowIndexByTypeID(state.secondCheckedType!.typeId!);
      } else {
        state.firstCheckedType = findPartJobTypeById(int.parse(parentIds[1]));
        //根据一级获取二级数据
        state.secondLevelList = findChildrenByTypeId(int.parse(parentIds[1]));
        //设置二级选中
        state.secondCheckedType = jobType;
        //清除三级
        state.thirdCheckedType = null;
        state.thirdLevelList = [];
        state.tempPartTypeName = state.secondCheckedType?.typeName;
        state.selectPartTypeText =
            "${state.firstCheckedType?.typeName}/${jobType.typeName}";
        state.checkedRowIndex =
            findRowIndexByTypeID(state.secondCheckedType!.typeId!);
      }
    }
    LogUtil.e("selectPartTypeText==${state.selectPartTypeText}");
    state.selectedPartTypeId = jobType.typeId;
    LogUtil.e("state.selectedPartTypeId==${state.selectedPartTypeId}");
    clearSerachText();
    getPartJobTypeTemp();
    update();
    Get.back();
  }

  clearSerachText() {
    state.jobSearchName = "";
    state.operator = "select";
    jobSearchEditController.text = "";
    state.searchDataList.clear();
  }

  ///监听地址输入
  updateAddress(String text) {
    state.addressText = text;
    update();
  }

  //清空地址输入
  clearAddress() {
    state.addressText = '';
    addressTextEditController.clear();
    addressTextFocusNode.unfocus();
    update();
  }

  ///监听内容输入
  updateWorkContent(String text) {
    state.workContent = text;
    update();
  }

  //清空内容输入
  clearWorkContent() {
    workContentEditController.clear();
    workContentFocusNode.unfocus();
    state.workContent = state.hinTextValue;
    workContentEditController = TextEditingController.fromValue(
      TextEditingValue(
        text: state.hinTextValue,
        selection: TextSelection.fromPosition(
          TextPosition(
              affinity: TextAffinity.downstream,
              offset: state.hinTextValue.length),
        ),
      ),
    );
    update();
  }

  //选择地区
  showCitySelector(context) async {
    Result? result2;
    if (Platform.isAndroid) {
      result2 = await CityPickers.showFullPageCityPicker(
          context: context, locationCode: state.locationCode);
    } else {
      result2 = await CityPickers.showCityPicker(
          context: context, locationCode: state.locationCode);
    }

    if (result2 != null) {
      state.countryText =
          "${result2.provinceName} ${result2.cityName} ${result2.areaName}";
      state.locationCode =
          result2.areaId == null ? result2.cityId! : result2.areaId!;
    } else {
      state.countryText = "";
      state.locationCode = "";
    }
    update();
    LogUtil.e(result2);
  }

  //设置一级选中
  changFisrtChecked(typeId) {
    LogUtil.e("typeId===$typeId");
    for (var item in state.firstLevelList) {
      if (item.typeId == typeId) {
        item.checked = true;
        state.firstCheckedType = item;
      } else {
        item.checked = false;
      }
    }
    state.secondLevelList = findChildrenByTypeId(typeId!);
    LogUtil.e(state.secondLevelList.length, tag: "右侧数据长度");
    update();
  }

  //设置二级选中
  changSecondChecked(typeId, rowIndex) {
    //先清空二三级选中
    clearListChecked("2");
    clearListChecked("3");
    for (var item in state.secondLevelList) {
      if (item.typeId == typeId) {
        item.checked = true;
        state.secondCheckedType = item;
        //清理三级选中
        state.thirdCheckedType = null;
        state.thirdLevelList = findChildrenByTypeId(typeId);
      } else {
        item.checked = false;
      }
    }
    state.checkedRowIndex = rowIndex;
    LogUtil.e(rowIndex, tag: "右侧二级选中的行:");
    LogUtil.e(state.thirdLevelList.length, tag: "右侧二级数据长度");
    update();
  }

  //设置三级选中
  changThirdChecked(int typeId) {
    for (int i = 0; i < state.thirdLevelList.length; i++) {
      if (state.thirdLevelList[i].typeId == typeId) {
        state.thirdLevelList[i].checked = true;
        state.thirdCheckedType = state.thirdLevelList[i];
      } else {
        state.thirdLevelList[i].checked = false;
      }
    }
    LogUtil.e(state.thirdCheckedType?.typeName, tag: "右侧三级数据选中");
    update();
  }

  //初始化1-2-3级的选中
  initPartJobTypeCheck() {
    PartJobType? jobType;
    if (state.selectedPartTypeId != null) {
      jobType = findPartJobTypeById(state.selectedPartTypeId!);
      if (jobType != null) {
        //清除所有选中
        clearListChecked("0");
        String typeIds = jobType.ancestors!;
        LogUtil.e(typeIds, tag: "typeIds:");
        LogUtil.e(state.checkedRowIndex, tag: "checkedRowIndex:");
        List<String>? typeList = typeIds.split(",");
        if (typeList.length == 2) {
          //只有一个上级
          changFisrtChecked(int.parse(typeList[1]));
          changSecondChecked(state.selectedPartTypeId!, state.checkedRowIndex);
        }
        if (typeList.length == 3) {
          //两个上级
          changFisrtChecked(int.parse(typeList[1]));
          changSecondChecked(int.parse(typeList[2]), state.checkedRowIndex);
          changThirdChecked(state.selectedPartTypeId!);
        }
      } else {
        changFisrtChecked(state.firstLevelList[0].typeId);
      }
    }
  }

  //清空选中 0表示全部清空
  clearListChecked(String level) {
    if (state.partTypeList.isNotEmpty) {
      for (var item in state.partTypeList) {
        if (level == "0") {
          item.checked = false;
        }
        if (item.level == level) {
          item.checked = false;
        }
      }
    }
  }

  //提交类型选择
  submitSelectType() {
    String? selectType;
    String? oldSelectText = state.selectPartTypeText;
    if (state.thirdCheckedType != null) {
      selectType =
          "${state.firstCheckedType?.typeName}/${state.secondCheckedType?.typeName}/${state.thirdCheckedType?.typeName}";
      state.selectedPartTypeId = state.thirdCheckedType?.typeId;
      state.tempPartTypeName = state.secondCheckedType?.typeName;
    } else {
      if (state.secondCheckedType != null) {
        selectType =
            "${state.firstCheckedType?.typeName}/${state.secondCheckedType?.typeName}";
        state.selectedPartTypeId = state.secondCheckedType?.typeId;
        state.tempPartTypeName = state.secondCheckedType?.typeName;
      }
    }

    if (state.selectedPartTypeId == 0) {
      EasyLoading.showToast("请选择兼职类型!");
      state.selectPartTypeText = oldSelectText;
      return false;
    }

    if (state.selectedPartTypeId != 0 &&
        state.thirdLevelList.isNotEmpty &&
        state.thirdCheckedType == null) {
      state.selectPartTypeText = oldSelectText;
      EasyLoading.showToast("请选择兼职子类型!");
      return false;
    }
    state.selectPartTypeText = selectType!;
    getPartJobTypeTemp();
    update();
    Get.back();
  }

  //处理场景选择
  updateWorkSceneChecked(WorkScene scene) {
    if (state.selectedPartTypeId != null && state.selectedPartTypeId != 0) {
      PartJobType jobType = findPartJobTypeById(state.selectedPartTypeId!);
      List<WorkScene>? sceneList = jobType.sceneList;
      if (sceneList != null) {
        for (var item in sceneList) {
          scene == item ? item.checked = true : item.checked = false;
        }
      }
      //设置选中场景
      state.selectedScene = scene.id!;
    }
    update();
  }

  //获取分类数据
  getPartJobTypeList() {
    JobApi().getPartJobType((data) {
      if (data is List<PartJobType>) {
        state.partTypeList = data;
        state.firstLevelList = findChildrenByTypeId(0);
        if (state.firstLevelList.isNotEmpty) {
          //处理一级初始
          state.firstCheckedType = state.partTypeList[0];
          state.firstCheckedType?.checked = true;
          state.secondLevelList =
              findChildrenByTypeId(state.partTypeList[0].typeId!);
          LogUtil.e(state.firstLevelList, tag: "顶级分类数据");
        }
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
    });
  }

  //获取分类模板
  getPartJobTypeTemp() {
    if (state.selectedPartTypeId != null && state.selectedPartTypeId != 0) {
      int? typeId;
      //如果选择的节点是三级则传递二级
      if (state.thirdLevelList.isNotEmpty) {
        typeId = state.secondCheckedType?.typeId;
      } else {
        typeId = state.selectedPartTypeId;
      }
      JobApi().getPartJobTypeTemp((data) {
        if (data is List<PartTypeTemp>) {
          state.partTypeTempList = data;
          if (state.partTypeTempList.isNotEmpty &&
              state.partTypeTempList.length > 1) {
            state.isShowNextButton = true;
          } else {
            state.isShowNextButton = false;
          }
          //默认选择第一个
          state.currentTempIndex = 0;
          state.showTempContent = state.partTypeTempList[0].tempContent!;
          LogUtil.e(state.showTempContent, tag: "state.showTempContent");
          update();
        } else {
          state.errorMsg = data;
          EasyLoading.showError(data["msg"]);
        }
      }, typeId!);
    }
  }

  //下一个模板
  getNextTempContent() {
    if (state.partTypeTempList.isNotEmpty) {
      int tempLen = state.partTypeTempList.length;
      LogUtil.e(tempLen);
      if (tempLen > 1 && state.currentTempIndex < tempLen - 1) {
        LogUtil.e(state.currentTempIndex);
        state.currentTempIndex++;
        state.showTempContent =
            state.partTypeTempList[state.currentTempIndex].tempContent!;
      } else {
        state.currentTempIndex = 0;
        state.showTempContent = state.partTypeTempList[0].tempContent!;
      }
    }
    update();
  }

  //回填模板内容到输入框
  submitTempContent() {
    if (state.showTempContent.isNotEmpty) {
      state.workContent = state.showTempContent;
    }
    workContentEditController = TextEditingController.fromValue(
      TextEditingValue(
        text: state.workContent,
        selection: TextSelection.fromPosition(
          TextPosition(
              affinity: TextAffinity.downstream,
              offset: state.workContent.length),
        ),
      ),
    );
    update();
    Get.back();
  }

  //根据ID查询
  findPartJobTypeById(int typeId) {
    PartJobType? jobType;
    if (state.partTypeList.isNotEmpty) {
      for (var item in state.partTypeList) {
        if (item.typeId == typeId) {
          jobType = item;
          break;
        }
      }
    }
    return jobType;
  }

  //根据名称查询
  findPartJobTypeByName(String typeName) {
    List<PartJobType> subList = [];
    List<PartJobType> resultList = [];
    if (state.partTypeList.isNotEmpty) {
      for (var item in state.partTypeList) {
        //排除顶级搜索结果
        if (item.typeName!.contains(typeName.trim()) && item.parentId != 0) {
          //查询下级 如果有下级就直接全部加入集合
          subList = findChildrenByTypeId(item.typeId!);
          if (subList.isNotEmpty) {
            resultList.addAll(subList);
          } else {
            if (!resultList.contains(item)) {
              resultList.add(item);
            }
          }
        }
      }
    }
    return resultList;
  }

  //查询下级分类
  findChildrenByTypeId(int parentId) {
    List<PartJobType> resultList = [];
    if (state.partTypeList.isNotEmpty) {
      for (var item in state.partTypeList) {
        if (item.parentId == parentId) {
          resultList.add(item);
        }
      }
    }
    return resultList;
  }

  findRowIndexByTypeID(int typeId) {
    int rowIndex = 0;
    LogUtil.e(typeId, tag: "typeId:");
    List<List<PartJobType>> rowData = dealListData(state.secondLevelList);
    if (rowData.isNotEmpty) {
      PartJobType? secondType;
      for (int i = 0; i < rowData.length; i++) {
        LogUtil.e(rowData[i], tag: "rowData[$i]:");
        secondType = findPartJobTypeById(typeId);
        if (rowData[i].contains(secondType)) {
          rowIndex = i;
          LogUtil.e(i, tag: "数据【${secondType?.typeName}】d对应的行号为:");
          break;
        }
      }
    }
    return rowIndex;
  }

  ///处理数据分组
  ///typeList 数据集合
  ///count 每组个数
  List<List<PartJobType>> dealListData(List<PartJobType> typeList,
      {int count = 2}) {
    List<List<PartJobType>> resultList = [];
    if (typeList.isNotEmpty) {
      int len = typeList.length;
      int remainder = len % count; //(先计算出余数)
      int number = len ~/ count; //然后是商
      if (0 != remainder) {
        number = number + 1;
      }
      for (int i = 0; i < number; i++) {
        List<PartJobType> subList = [];
        if (i < number - 1) {
          subList = typeList.sublist(i * count, (i + 1) * count);
        } else {
          subList = typeList.sublist(count * (number - 1), len);
        }
        resultList.add(subList);
      }
    }
    return resultList;
  }

  //提交基本信息到缓存
  submitBasicPartTimeJob() {
    clearFocus();
    //岗位基本信息
    Map<String, dynamic> basicJobData = {};

    if (state.jobName.isEmpty) {
      EasyLoading.showToast("请输入岗位名称!");
      return;
    }
    basicJobData["jobName"] = state.jobName;

    if (state.selectedPartTypeId == 0 || state.selectPartTypeText.isEmpty) {
      EasyLoading.showToast("请输入岗位类型!");
      return;
    }
    basicJobData["jobType"] = state.selectedPartTypeId;

    if (state.workContent.isEmpty) {
      EasyLoading.showToast("请输入招聘内容!");
      return;
    }
    basicJobData["jobDesc"] = state.workContent;

    if (state.countryText.isEmpty) {
      EasyLoading.showToast("请选择工作地点!");
      return;
    }
    basicJobData["provinceName"] = state.countryText.split(" ")[0];
    basicJobData["cityName"] = state.countryText.split(" ")[1];
    basicJobData["areaName"] = state.countryText.split(" ")[2];
    basicJobData["workScene"] = state.selectedScene;

    if (state.addressText.isEmpty) {
      EasyLoading.showToast("请输入详细地址!");
      return;
    }
    basicJobData["address"] = state.addressText;
    //数据存入缓存
    StorageService.to
        .setString(partTimeJobData, basicJobData.toString())
        .then((data) {
      if (data) {
        //缓存成功进入下一步页面
        LogUtil.e(basicJobData, tag: "保存基本数据：");
        Get.toNamed(PartDetailPage.routeName, arguments: basicJobData);
      }
    });
  }
}
